<template>
  <view class="bac-col-fa min-h-100 bottom-index">
    <!-- 加载中蒙版 -->
    <qmy-mask-load :dataLoaded="dataLoaded"></qmy-mask-load>
    <!-- #ifdef MP-WEIXIN -->
    <!-- 顶部导航 -->
    <qmy-custom-navbar :top="42" :title="'圈子管理'"></qmy-custom-navbar>
    <!-- #endif -->
    <view :style="{paddingTop:menuObject.top + menuObject.height + 'px'}">
      <v-tabs :fixed="true" :scroll="false" :pills="true" bgColor="#ffffff00" pillsColor="#ffffff00"
              fontSize="30rpx" activeFontSize="32rpx" lineHeight="40rpx"
              activeColor="linear-gradient(to right, #1e1e1e, #1e1e1e)"
              color="linear-gradient(to right, #616161, #616161)" bold lineColor="#14cc60" v-model="current"
              :tabs="tabs"></v-tabs>
    </view>
    <!-- 悬浮球 -->
    <!-- <drag-button :isDock="true" :existTabBar="true" @btnClick="btnClick" /> -->
    <!-- 发布弹窗 -->
    <uni-popup ref="publishpopup" type="bottom" background-color="#ffffff" border-radius="20rpx 20rpx 0 0">
      <view class="publish-rectangle">
        <view class="mt-40 padding-50">
          <view class="flex-dir-row ali-item-cen flex-x-bet">
            <view class="box-1" @tap="$NavigateTo('/pages/publish/article')">
              <image src="https://mp-1a195ae8-6052-4d67-9e67-d73bf0b3c084.cdn.bspapp.com/fzx.png"
                     class="image-1">
              </image>
              <view class="flex-x-bet flex-dir-col full-height">
                <view class="fs-40 fw-600">发圈子</view>
                <view class="fs-28 col-54">分享美好瞬间</view>
              </view>
            </view>
            <view class="box-2" @tap="navToPublish('/pages/publish/notice')">
              <image src="https://mp-1a195ae8-6052-4d67-9e67-d73bf0b3c084.cdn.bspapp.com/ftz.png"
                     class="image-2">
              </image>
              <view class="flex-x-bet flex-dir-col full-height">
                <view class="fs-40 fw-600">发通知</view>
                <view class="fs-28 col-54 mt-10">通知成员活动事项</view>
              </view>
            </view>
          </view>
          <view class="box-3" @click="navToPublish('/pages/publish/activity')">
            <image src="https://mp-1a195ae8-6052-4d67-9e67-d73bf0b3c084.cdn.bspapp.com/fhd.png"
                   class="image-3">
            </image>
            <view class="flex-x-bet flex-dir-col full-height">
              <view class="fs-40 fw-600">发活动</view>
              <view class="fs-28 col-54 mt-10">开始组织你的活动</view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
    <view class="ping-30">
      <!-- 如果圈子列表为空 -->
      <view v-if="circleData.length == 0 || filteredCircleData.length == 0" class="activity-empty-box">
        <image class="activity-empty-image"
               src="https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/circle-empty.png"
               mode="scaleToFill"/>
        <view class="fs-28 fw-600">暂无圈子</view>
      </view>
      <view v-else>
        <view v-for="(item,index) in filteredCircleData" :key="index"
              class="bac-col-f br-20 mt-10 pos-rela mb-30 animate__fadeIn dh-0-4s" style="z-index: 1;">
          <view class="ping-30">
            <view class="flex-dir-row flex-x-bet ali-item-cen">
              <view class="flex-dir-row flex-x-bet ali-item-sta w-100">
                <view class="flex-dir-row ali-item-cen">
                  <qmy-gender-border :gender="item.userGender || item.user_gender"
                                     :avatar="item.userAvatar || item.user_avatar || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'"
                                     :avatarWidth="75 + 'rpx'" :avatarHeight="75 + 'rpx'"></qmy-gender-border>
                  <view class="ml-20">
                    <view class="fs-26 fw-600 flex-dir-row ali-item-cen">
                      <view class="text-element-1">{{ item.userName || item.user_name || '匿名用户' }}</view>
                      <view v-if="item.isEssence || item.is_essence" class="fs-20 highlighted">精选</view>
                    </view>
                    <view class="fs-24 col-b1 mt-5">
                      {{
                        $timeFormat(item.lastModifyDate || item.last_modify_date || item.publishDate || item.publish_date || item.createTime)
                      }}
                    </view>
                  </view>
                </view>
                <view>
                  <view @tap="taptext($event,index)" class="iconfont ic-dian fs-48"></view>
                  <chunLei-popups v-model="isBubble" :popData="bubbleData" direction="row"
                                  @tapPopup="tapPopup" :x="bubbleX" :y="bubbleY" placement="top-end" dynamic>
                  </chunLei-popups>
                </view>
              </view>
            </view>
            <view class="mt-20" @click="$NavigateTo(`/pages/detail/articleDetail?id=${item.id || item._id}`)">
              <view class="fs-28 text-element-4">
                {{ item.title }}
              </view>
              <!-- 安全检查图片数组 -->
              <image v-if="item.images && item.images.length == 1" class="br-20 mt-20 image-280"
                     :src="item.images[0]" mode="aspectFill">
              </image>
              <image v-else-if="item.thumbnail && item.thumbnail.length == 1" class="br-20 mt-20 image-280"
                     :src="item.thumbnail[0]" mode="aspectFill">
              </image>

              <view v-else-if="item.images && item.images.length == 2" class="flex-dir-row flex-x-bet">
                <image v-for="(url,its) in item.images"
                       :class="its == 0?'brtl-20 brbl-20':'brtr-20 brbr-20'" :key="its"
                       class="mt-20 image-3125" :src="url" mode="aspectFill">
                </image>
              </view>
              <view v-else-if="item.thumbnail && item.thumbnail.length == 2" class="flex-dir-row flex-x-bet">
                <image v-for="(url,its) in item.thumbnail"
                       :class="its == 0?'brtl-20 brbl-20':'brtr-20 brbr-20'" :key="its"
                       class="mt-20 image-3125" :src="url" mode="aspectFill">
                </image>
              </view>

              <view v-else-if="item.images && item.images.length >= 3" class="flex-dir-row flex-x-bet">
                <image v-for="(url,its) in item.images.slice(0,3)"
                       :class="its == 0?'brtl-20 brbl-20':its == 1?'':'brtr-20 brbr-20'" :key="its"
                       class="mt-20 image-205" :src="url" mode="aspectFill">
                </image>
              </view>
              <view v-else-if="item.thumbnail && item.thumbnail.length >= 3" class="flex-dir-row flex-x-bet">
                <image v-for="(url,its) in item.thumbnail.slice(0,3)"
                       :class="its == 0?'brtl-20 brbl-20':its == 1?'':'brtr-20 brbr-20'" :key="its"
                       class="mt-20 image-205" :src="url" mode="aspectFill">
                </image>
              </view>
            </view>
            <view>
              <view class="flex-x-bet ali-item-cen flex-dir-row mt-20">
                <view>
                  <view v-if="item.activityId || item.activity_id"
                        @click="$NavigateTo(`../detail/detail?id=${item.activityId || item.activity_id}`)"
                        class="br-200 flex-dir-row ali-item-cen border-bf padding-5-15">
                    <image v-if="item.activityImg && item.activityImg.length > 0" class="image-28"
                           :src="item.activityImg[0].src" mode="aspectFill">
                    </image>
                    <image v-else-if="item.activity_img && item.activity_img.length > 0" class="image-28"
                           :src="item.activity_img[0].src" mode="aspectFill">
                    </image>
                    <view class="fs-26 ml-10 text-element-1">{{ item.activityName || item.activity_name }}</view>
                  </view>
                </view>
                <view class="flex-dir-row ali-item-cen col-87">
                  <view class="flex-dir-row ali-item-cen">
                    <view class="iconfont ic-talk-line fs-46"></view>
                    <view class="fs-28 ml-5">{{ item.commentCount || item.comment_count || 0 }}</view>
                  </view>
                  <view @click="likeCircle(item.id || item._id)" class="flex-dir-row ali-item-cen ml-20">
                    <view class="iconfont fs-46 "
                          :class="(item.likeUserIds && item.likeUserIds.includes(userInfo.id)) || (item.like_user_id && item.like_user_id.includes(userInfo.id))?'ic-nice col-00ba31':'ic-nice-line col-87'">
                    </view>
                    <view class="fs-28 ml-5">{{
                        (item.likeUserIds && item.likeUserIds.length) || (item.like_user_id && item.like_user_id.length) || 0
                      }}
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载状态提示 -->
        <view class="load-more-container" v-if="dataLoaded">
          <view v-if="loading" class="load-more-loading">
            <view class="loading-icon"></view>
            <view class="fs-26 col-87 ml-10">加载中...</view>
          </view>
          <view v-else-if="!hasMore && circleData.length > 0" class="load-more-end">
            <view class="fs-26 col-87">没有更多数据了</view>
          </view>
          <view v-else-if="hasMore && circleData.length > 0" class="load-more-tip">
            <view class="fs-26 col-87">上拉加载更多</view>
          </view>
        </view>

<!--        <qmy-logo></qmy-logo>-->
      </view>
    </view>
    <!-- 底部定位发布按钮 -->
    <view class="w-100 fixed-bottom bac-col-00b" @click="btnClick">
      <view class="w-100 bg-col-00b text-ali-c">
        <view class="fs-30 col-f fw-600">我要发布</view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  store,
  mutations
} from '@/utils/store.js'

import {getMyPostListApi} from '@/api/post/posts';


export default {
  data() {
    return {
      // #ifdef MP-WEIXIN
      menuObject: uni.getMenuButtonBoundingClientRect(),
      // #endif
      // #ifndef MP-WEIXIN
      menuObject: 0,
      // #endif
      tabs: ['全部', '审核中', '审核失败'],
      circleData: [], // 我发布的圈子列表
      dataLoaded: false, // 加载完成状态
      isBubble: false,
      bubbleX: 0,
      bubbleY: 0,
      bubbleData: [{
        title: '修改'
      }, {
        title: '删除'
      }],
      selectedIndex: 0,
      current: 0,
      tokenExpired: null,
      // 分页相关参数
      pageNumber: 1, // 当前页码
      pageSize: 10, // 每页数量
      hasMore: true, // 是否还有更多数据
      loading: false, // 是否正在加载
      total: 0, // 总数据量
    }
  },
  computed: {
    userInfo() {
      // token过期检查已在认证管理器中处理
      this.tokenExpired = Date.now() + 24 * 60 * 60 * 1000;
      return store.userInfo //用户信息
    },
    filteredCircleData() {
      return this.circleData.filter(item => {
        if (this.current === 0) return true;
        // 兼容不同的字段名
        const auditStatus = item.auditStatus;
        if (this.current === 1) return auditStatus === 0 || auditStatus === 1;
        if (this.current === 2) return auditStatus === 2 || auditStatus === 3;
        return true;
      });
    }
  },
  watch: {
    // 监听标签切换，重新加载数据
    current(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.getMyCircleData(false);
      }
    }
  },
  onLoad() {
    // 获取我发布的圈子列表
    this.getMyCircleData();
  },
  // 监听页面滚动到底部
  onReachBottom() {
    // 加载更多数据
    this.getMyCircleData(true);
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.getMyCircleData(false);
    // 停止下拉刷新
    setTimeout(() => {
      uni.stopPullDownRefresh();
    }, 1000);
  },
  methods: {
    btnClick() {
      this.$refs.publishpopup.open('bottom')
    },
    async navToPublish(path) {
      // 如果未登录或登录过期，跳转到登录页
      if (!this.userInfo.id || this.tokenExpired < Date.now()) {
        this.$NavigateTo('/qmy_user/login')
        return
      }
      if (this.userInfo?.role?.includes('organizer')) {
        this.$NavigateTo(path)
        return
      }
      // 先更新用户信息，看用户是否是组织者
      await mutations.updateUserInfo()
      if (this.userInfo?.role?.includes('organizer')) {
        this.$NavigateTo(path)
      } else {
        this.$Toast(path == '/pages/publish/notice' ? '您还没有发布活动，不能发送通知哦' : '您还没有权限发布活动，快去认证吧')
      }
    },
    tapPopup(e) {
      if (e.title == '修改') {
        let that = this;
        uni.navigateTo({
          url: `/pages/publish/article?id=${this.circleData[this.selectedIndex].id || this.circleData[this.selectedIndex]._id}`,
          events: {
            refreshData: () => {
              that.getMyCircleData();
            }
          }
        })
      } else {
        this.deleteCircle(this.circleData[this.selectedIndex].id || this.circleData[this.selectedIndex]._id);
      }
    },
    taptext(e, index) {
      this.bubbleX = e.touches[0].clientX;
      this.bubbleY = e.touches[0].clientY;
      this.isBubble = !this.isBubble;
      this.selectedIndex = index;
    },
    // 获取我发布的圈子列表
    getMyCircleData(loadMore = false) {
      // 如果是加载更多，但没有更多数据或正在加载中，则返回
      if (loadMore && (!this.hasMore || this.loading)) {
        return;
      }

      // 如果不是加载更多，重置分页参数
      if (!loadMore) {
        this.pageNumber = 1;
        this.hasMore = true;
        this.circleData = [];
        this.dataLoaded = false;
      }

      this.loading = true;

      // 构建请求参数
      const params = {
        pageNumber: this.pageNumber,
        pageSize: this.pageSize
      };

      getMyPostListApi(params).then((res) => {
        console.log(res.data.data)

        const pageData = res.data.data;
        let records = Array.isArray(pageData.records) ? pageData.records : [];

        // 处理数据格式，将字符串格式的JSON数组解析为真正的数组
        records = records.map(item => {
          // 处理images字段
          if (item.images && typeof item.images === 'string') {
            try {
              item.images = JSON.parse(item.images);
            } catch (e) {
              console.warn('解析images字段失败:', e);
              item.images = [];
            }
          }

          // 处理thumbnail字段（如果存在）
          if (item.thumbnail && typeof item.thumbnail === 'string') {
            try {
              item.thumbnail = JSON.parse(item.thumbnail);
            } catch (e) {
              console.warn('解析thumbnail字段失败:', e);
              item.thumbnail = [];
            }
          }

          // 处理like_user_id字段（如果存在且为字符串）
          if (item.like_user_id && typeof item.like_user_id === 'string') {
            try {
              item.like_user_id = JSON.parse(item.like_user_id);
            } catch (e) {
              console.warn('解析like_user_id字段失败:', e);
              item.like_user_id = [];
            }
          }

          // 处理likeUserIds字段（如果存在且为字符串）
          if (item.likeUserIds && typeof item.likeUserIds === 'string') {
            try {
              item.likeUserIds = JSON.parse(item.likeUserIds);
            } catch (e) {
              console.warn('解析likeUserIds字段失败:', e);
              item.likeUserIds = [];
            }
          }

          // 处理activity_img字段（如果存在且为字符串）
          if (item.activity_img && typeof item.activity_img === 'string') {
            try {
              item.activity_img = JSON.parse(item.activity_img);
            } catch (e) {
              console.warn('解析activity_img字段失败:', e);
              item.activity_img = [];
            }
          }

          // 处理activityImg字段（如果存在且为字符串）
          if (item.activityImg && typeof item.activityImg === 'string') {
            try {
              item.activityImg = JSON.parse(item.activityImg);
            } catch (e) {
              console.warn('解析activityImg字段失败:', e);
              item.activityImg = [];
            }
          }

          // 确保数组类型字段不为null或undefined
          if (!Array.isArray(item.images)) item.images = [];
          if (!Array.isArray(item.thumbnail)) item.thumbnail = [];
          if (!Array.isArray(item.like_user_id)) item.like_user_id = [];
          if (!Array.isArray(item.likeUserIds)) item.likeUserIds = [];
          if (!Array.isArray(item.activity_img)) item.activity_img = [];
          if (!Array.isArray(item.activityImg)) item.activityImg = [];

          return item;
        });

        // 更新数据
        if (loadMore) {
          // 加载更多：追加数据
          this.circleData = this.circleData.concat(records);
        } else {
          // 首次加载：替换数据
          this.circleData = records;
        }

        // 更新分页信息
        this.total = pageData.total || 0;
        this.hasMore = this.pageNumber < (pageData.pages || 1);

        // 如果有更多数据，页码+1
        if (this.hasMore) {
          this.pageNumber++;
        }

        this.dataLoaded = true;
        this.loading = false;

      }).catch((err) => {
        console.error('遇到错误:', err); // 打印错误信息
        let {
          code,
          msg
        } = this.$parseError(err); // 调用公共解析方法
        this.$Toast(msg);
        // 确保即使出错也设置为空数组
        if (!loadMore) {
          this.circleData = [];
        }
        this.dataLoaded = true;
        this.loading = false;
        setTimeout(() => {
          if (code === 401) {
            this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
          }
        }, 1000);
      });
    },
    // 删除圈子
    deleteCircle(id) {
      this.$Route('update-private-data').deleteCircle(id).then((res) => {
        this.$Toast(res.msg);
        setTimeout(() => {
          this.getMyCircleData();
        }, 1000);
      }).catch((err) => {
        console.error('遇到错误:', err); // 打印错误信息
        let {
          code,
          msg
        } = this.$parseError(err); // 调用公共解析方法
        this.$Toast(msg);
        setTimeout(() => {
          if (code === 401) {
            this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
          }
        }, 1000);
      });
    },
    //点赞、取消点赞
    likeCircle(id) {
      // 点赞节流
      this.$debounce(() => {
        // 点赞或取消点赞时先更新点赞状态点赞数，等待返回在确认是否复原
        this.circleData.forEach(item => {
          const itemId = item.id || item._id;
          if (itemId == id) {
            // 兼容不同的字段名
            const likeUserIds = item.likeUserIds || item.like_user_id || [];
            const userId = this.userInfo.id || this.userInfo._id;

            if (likeUserIds.includes(userId)) {
              const index = likeUserIds.indexOf(userId);
              likeUserIds.splice(index, 1);
            } else {
              likeUserIds.push(userId);
            }

            // 更新到对应的字段
            if (item.likeUserIds) {
              item.likeUserIds = likeUserIds;
            }
            if (item.like_user_id) {
              item.like_user_id = likeUserIds;
            }
          }
        })
        this.$Route('add-private-data', true).likeCircle(id).then((res) => {
          // 不用刷新数据无影响且禁止刷新数据,会影响分页！
          // this.getMyCircleData();
        }).catch((err) => {
          // 恢复原状态
          this.circleData.forEach(item => {
            const itemId = item.id || item._id;
            if (itemId == id) {
              const likeUserIds = item.likeUserIds || item.like_user_id || [];
              const userId = this.userInfo.id || this.userInfo._id;

              if (likeUserIds.includes(userId)) {
                const index = likeUserIds.indexOf(userId);
                likeUserIds.splice(index, 1);
              } else {
                likeUserIds.push(userId);
              }

              // 更新到对应的字段
              if (item.likeUserIds) {
                item.likeUserIds = likeUserIds;
              }
              if (item.like_user_id) {
                item.like_user_id = likeUserIds;
              }
            }
          })
          console.error('遇到错误:', err); // 打印错误信息
          let {
            code,
            msg
          } = this.$parseError(err); // 调用公共解析方法
          this.$Toast(msg);
          setTimeout(() => {
            if (code === 401) {
              this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
            }
          }, 1000);
        });
      }, 500, true, "likeCircle")
    },
  }
}
</script>

<style lang="scss">
.image-130 {
  height: 130rpx;
}

.image-110 {
  width: 110rpx;
  height: 110rpx;
}

.image-75 {
  width: 75rpx;
  height: 75rpx;
}

.image-280 {
  height: 280rpx;
  max-width: 100%;
}

.image-205 {
  height: 205rpx;
  width: 205rpx;
}

.image-28 {
  width: 28rpx;
  height: 28rpx;
  border-radius: 5rpx;
}

.image-3125 {
  height: 260rpx;
  width: 312rpx;
}

.highlighted {
  background: #ffe75c;
  width: 65rpx;
  height: 32rpx;
  line-height: 32rpx;
  border-radius: 10rpx;
  color: #fff;
  text-align: center;
  margin-left: 10rpx;
}

.padding-5-15 {
  padding: 5rpx 15rpx;
}

.edit-btn {
  width: 50%;
  height: 90rpx;
  text-align: center;
  border-bottom-right-radius: 20rpx;
  line-height: 90rpx;
}

.red-btn {
  width: 50%;
  height: 90rpx;
  text-align: center;
  border-bottom-left-radius: 20rpx;
  line-height: 90rpx;
  background: #ff0000;
  color: #fff;
}

.publish-rectangle::before {
  content: '';
  position: absolute;
  top: -95rpx;
  z-index: -1;
  left: 0;
  width: 100%;
  height: 50%;
  background-color: white;
  transform: skewY(3deg);
  border-radius: 40rpx 40rpx 0 0;
}

.padding-50 {
  padding: 50rpx;
}

.full-height {
  height: 100%;
}

.box-1 {
  background: #cae8ff;
  border-radius: 20rpx;
  position: relative;
  padding: 45rpx 35rpx;
  width: 48%;
  height: 190rpx;
  z-index: 4;
}

.image-1 {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 170rpx;
  height: 170rpx;
  z-index: 4;
}

.box-2 {
  background: #f2fa91;
  border-radius: 20rpx;
  position: relative;
  padding: 45rpx 35rpx;
  width: 48%;
  height: 190rpx;
  z-index: 4;
}

.image-2 {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 135rpx;
  height: 170rpx;
  z-index: 4;
}

.box-3 {
  background: #a9f5c3;
  border-radius: 20rpx;
  position: relative;
  padding: 45rpx 35rpx;
  width: 100%;
  height: 190rpx;
  margin-top: 30rpx;
  z-index: 4;
}

.image-3 {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 220rpx;
  height: 220rpx;
  z-index: 4;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  width: 100%;
  padding-top: 30rpx;
  padding-bottom: 30rpx !important;
  padding-bottom: calc(30rpx + constant(safe-area-inset-bottom)) !important;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom)) !important;
  z-index: 99;
  transition: background-color 0.2s ease;
}

.fixed-bottom:active {
  background-color: #11b051 !important;
  /* 点击时背景颜色变化 */
}

/* 加载状态样式 */
.load-more-container {
  padding: 30rpx 0;
  text-align: center;
}

.load-more-loading {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-icon {
  width: 30rpx;
  height: 30rpx;
  border: 3rpx solid #e0e0e0;
  border-top: 3rpx solid #14cc60;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.load-more-end,
.load-more-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
}
</style>
